import React, { useState, useEffect, useRef } from 'react';
import { Input, Upload, Button, message, Spin, Avatar, Image } from 'antd';
import { SendOutlined, PictureOutlined } from '@ant-design/icons';
import ChatMessage from '@/components/ChatMessage/ChatMessage';
import axios from 'axios';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import './Chat.page.css'; // Reusing the existing CSS
import './AiChat.css'; // 我们将添加一些额外的样式

interface Message {
    content: string;
    type: 'text' | 'image';
    sender: 'user' | 'expert';
    timestamp?: string;
}

const AiChat: React.FC = () => {
    const [messages, setMessages] = useState<Message[]>([]);
    const [inputText, setInputText] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const messagesEndRef = useRef<HTMLDivElement>(null);

    // Scroll to bottom whenever messages change
    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    const handleSendMessage = async () => {
        if (!inputText.trim()) return;

        // Add user message to chat
        const userMessage: Message = {
            content: inputText,
            type: 'text',
            sender: 'user',
            timestamp: new Date().toISOString(),
        };

        setMessages(prev => [...prev, userMessage]);
        setInputText('');
        setIsLoading(true);

        try {
            // Prepare conversation history for API
            const historyMessages = messages.map(msg => ({
                role: msg.sender === 'user' ? 'user' : 'assistant',
                content: msg.content
            }));

            // Add current user message
            historyMessages.push({
                role: 'user',
                content: inputText
            });

            // Call Deepseek API through our backend
            const response = await axios.post('/app-api/ai-chat', {
                messages: historyMessages,
                stream: false
            });

            if (response.data && response.data.choices && response.data.choices.length > 0) {
                const aiResponse = response.data.choices[0].message.content;

                // Add AI response to chat
                const aiMessage: Message = {
                    content: aiResponse,
                    type: 'text',
                    sender: 'expert',
                    timestamp: new Date().toISOString(),
                };

                setMessages(prev => [...prev, aiMessage]);
            } else {
                throw new Error('Invalid response format');
            }
        } catch (error) {
            console.error('Error sending message to AI:', error);
            message.error('发送消息失败，请重试');

            // Add error message
            const errorMessage: Message = {
                content: '抱歉，发生了错误，请重试。',
                type: 'text',
                sender: 'expert',
                timestamp: new Date().toISOString(),
            };

            setMessages(prev => [...prev, errorMessage]);
        } finally {
            setIsLoading(false);
        }
    };

    const handleImageUpload = async (info: any) => {
        const { status, response } = info.file;

        if (status === 'uploading') {
            // Show uploading message
            const tempMessage: Message = {
                content: '图片上传中...',
                type: 'text',
                sender: 'user',
                timestamp: new Date().toISOString(),
            };
            setMessages(prev => [...prev, tempMessage]);
        } else if (status === 'done' && response?.url) {
            // Remove uploading message
            setMessages(prev => prev.filter(msg =>
                !(msg.content === '图片上传中...' && msg.sender === 'user')
            ));

            // Add image message
            const imageMessage: Message = {
                content: response.url,
                type: 'image',
                sender: 'user',
                timestamp: new Date().toISOString(),
            };
            setMessages(prev => [...prev, imageMessage]);
            setIsLoading(true);

            try {
                // Process image with Deepseek API
                const aiResponse = await axios.post('/app-api/ai-recognize-image', {
                    imageUrl: response.url
                });

                if (aiResponse.data && aiResponse.data.description) {
                    const aiMessage: Message = {
                        content: aiResponse.data.description,
                        type: 'text',
                        sender: 'expert',
                        timestamp: new Date().toISOString(),
                    };

                    setMessages(prev => [...prev, aiMessage]);
                } else {
                    throw new Error('Invalid response format');
                }
            } catch (error) {
                console.error('Error processing image:', error);
                message.error('图片处理失败，请重试');

                const errorMessage: Message = {
                    content: '抱歉，图片处理失败，请重试。',
                    type: 'text',
                    sender: 'expert',
                    timestamp: new Date().toISOString(),
                };

                setMessages(prev => [...prev, errorMessage]);
            } finally {
                setIsLoading(false);
            }
        } else if (status === 'error') {
            // Remove uploading message
            setMessages(prev => prev.filter(msg =>
                !(msg.content === '图片上传中...' && msg.sender === 'user')
            ));

            const errorMessage: Message = {
                content: '图片上传失败，请重试',
                type: 'text',
                sender: 'user',
                timestamp: new Date().toISOString(),
            };
            setMessages(prev => [...prev, errorMessage]);
        }
    };

    return (
        <div className="chat-container">
            <div className="messages-container">
                {messages.map((msg, index) => (
                    <div className={`message-wrapper ${msg.sender}`} key={index}>
                        <Avatar
                            src={msg.sender === 'user' ? '/user-avatar.svg' : '/expert-avatar.svg'}
                            size={40}
                            className="avatar"
                            alt={msg.sender === 'user' ? '用户' : '专家'}
                        />
                        <div className={`message w-full ${msg.sender}`}>
                            {msg.type === 'text' ? (
                                msg.sender === 'expert' ? (
                                    <div className="markdown-content">
                                        <ReactMarkdown remarkPlugins={[remarkGfm]}>
                                            {msg.content}
                                        </ReactMarkdown>
                                    </div>
                                ) : (
                                    <p>{msg.content}</p>
                                )
                            ) : (
                                <Image
                                    src={msg.content}
                                    width={200}
                                    alt="Disease Image"
                                    preview={{
                                        mask: '查看大图'
                                    }}
                                />
                            )}
                        </div>
                    </div>
                ))}
                {isLoading && (
                    <div className="loading-message">
                        <Spin size="small" /> 正在思考中...
                    </div>
                )}
                <div ref={messagesEndRef} />
            </div>
            <div className="input-container">
                <Input
                    value={inputText}
                    onChange={(e) => setInputText(e.target.value)}
                    onPressEnter={handleSendMessage}
                    placeholder="输入消息..."
                    disabled={isLoading}
                />
                <Button
                    type="primary"
                    icon={<SendOutlined />}
                    onClick={handleSendMessage}
                    disabled={isLoading || !inputText.trim()}
                >
                    发送
                </Button>
            </div>
        </div>
    );
};

export default AiChat;